package org.example.hansp.reflection.reflecAccessProperty;

import org.junit.jupiter.api.Test;

import java.lang.reflect.Field;

public class ReflecAccessProperty {
    Class<Student> studentClass=Student.class;
    Student student = studentClass.newInstance();

    public ReflecAccessProperty() throws InstantiationException, IllegalAccessException {
    }

    @Test
    public void test() throws NoSuchFieldException, InstantiationException, IllegalAccessException {
        Field name = studentClass.getField("name");

        name.set(student,"Lim");
        System.out.println(name.get(student));

    }
    @Test
    public void test2() throws NoSuchFieldException, InstantiationException, IllegalAccessException {

        Field age = studentClass.getDeclaredField("age");
        age.setAccessible(true);//对age进行爆破，可以操作private属性
        age.set(student,20);
        System.out.println(age.get(student));
    }
    @Test
    public void test3() throws NoSuchFieldException, InstantiationException, IllegalAccessException {
        Field sex=studentClass.getDeclaredField("sex");
        sex.setAccessible(true);
//        sex.set(student,'m');
        sex.set(null,'m');//因为sex是static属性，是所有对象共享的，所以student也可以写成null
        System.out.println(sex.get(student));
    }
}

class Student{
    public String name;
    private  int age;
    private static char sex;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public static char getSex() {
        return sex;
    }

    public static void setSex(char sex) {
        Student.sex = sex;
    }
}